import Message from '../../../miniprogram_npm/tdesign-miniprogram/message/index';

Page({
  data: {
    motorcycleName: '',
    motorcycleNameInputStatus: 'default',
    inputTips: '',
    otr: null,
    vehicleAge: 0,
    remainingRideableYears: 0,
    salvageValue: 0,
    ninetyPercentSalvageValue: 0,
    eightyPercentSalvageValue: 0,
    seventyPercentSalvageValue: 0,
    showWithInput: false,
    mode: '',
    dateVisible: false,
    date: new Date().getTime(),
    // 指定选择区间起始值
    start: '2012-03-15 00:00:00',
    end: '2025-03-15 00:00:00',
    filter(type, options) {
      if (type === 'year') {
        return options.sort((a, b) => b.value - a.value);
      }
      return options;
    },
    popupProps: {
      usingCustomNavbar: true,
    },
    priceError: false,
    priceFormat: (v) => {
      const isNumber = /^\d+(\.\d+)?$/.test(v);
      if (isNumber) {
        return parseFloat(v).toFixed(2);
      }
      return v;
    },
  },
  calculateCarScrapInfo(scrapStartDate, ortPrice) {
    const now = new Date();
    const startDate = new Date(scrapStartDate);

    // 计算车龄（几年，几个月）
    let years = now.getFullYear() - startDate.getFullYear();
    let months = now.getMonth() - startDate.getMonth();
    if (now.getDate() < startDate.getDate()) {
      months--;
    }
    if (months < 0) {
      years--;
      months += 12;
    }
    const vehicleAge = `${years} 年 ${months} 个月`;

    // 计算还可以骑多少年（几年，几个月）
    let remainingYears = 13 - years;
    let remainingMonths = 0 - months;
    if (remainingMonths < 0) {
      remainingYears--;
      remainingMonths += 12;
    }
    const remainingRideableYears = `${remainingYears} 年 ${remainingMonths} 个月`;

    // 计算按照比例的目前残值
    const salvageRate = (years + months / 12) / 13;
    const salvageValue = (ortPrice * (1 - salvageRate)).toFixed(2);

    // 计算不同残值率的价值
    const ninetyPercentSalvageValue = (salvageValue * 0.9).toFixed(2);
    const eightyPercentSalvageValue = (salvageValue * 0.8).toFixed(2);
    const seventyPercentSalvageValue = (salvageValue * 0.7).toFixed(2);

    // 更新页面数据
    this.setData({
      vehicleAge,
      remainingRideableYears,
      salvageValue,
      ninetyPercentSalvageValue,
      eightyPercentSalvageValue,
      seventyPercentSalvageValue
    });
  },
  onLoad(options) {
    // 获取当前日期
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    // 计算13年前的日期
    const thirteenYearsAgo = new Date(now);
    thirteenYearsAgo.setFullYear(thirteenYearsAgo.getFullYear() - 13);
    const thirteenYearsAgoYear = thirteenYearsAgo.getFullYear();
    const thirteenYearsAgoMonth = String(thirteenYearsAgo.getMonth() + 1).padStart(2, '0');
    const thirteenYearsAgoDay = String(thirteenYearsAgo.getDate()).padStart(2, '0');
    const thirteenYearsAgoHours = String(thirteenYearsAgo.getHours()).padStart(2, '0');
    const thirteenYearsAgoMinutes = String(thirteenYearsAgo.getMinutes()).padStart(2, '0');
    const thirteenYearsAgoSeconds = String(thirteenYearsAgo.getSeconds()).padStart(2, '0');

    // 格式化日期字符串
    const startDate = `${thirteenYearsAgoYear}-${thirteenYearsAgoMonth}-${thirteenYearsAgoDay} ${thirteenYearsAgoHours}:${thirteenYearsAgoMinutes}:${thirteenYearsAgoSeconds}`;
    const endDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    // 更新页面数据
    this.setData({
      start: startDate,
      end: endDate
    });
    const {
      otr,
      scrapStartDate,
      motorcycleName
    } = options;
    this.setData({
      otr: otr ?? "9.9",
      scrapStartDate: scrapStartDate,
      motorcycleName: motorcycleName && motorcycleName !== 'undefined' && motorcycleName !== 'null' ? motorcycleName : ''
    })
    this.calculateCarScrapInfo(scrapStartDate, otr);
  },
  onPriceInput(e) {
    const isNumber = /^\d+(\.\d+)?$/.test(e.detail.value);
    if (isNumber) {
      this.calculateCarScrapInfo(this.data.scrapStartDate, this.data.otr);
      this.setData({
        priceError: false
      })
    } else {
      this.setData({
        priceError: true
      });
    }
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;
    const {
      mode
    } = this.data;

    this.setData({
      [mode]: value,
      [`${mode}Data`]: value,
    });
  },
  onColumnChange(e) {
    console.log('pick', e.detail.value);
  },
  updateMotorcycleList(motorcycleName, otr) {
    // 从本地存储中获取 motorcycleList 数组
    let motorcycleList = wx.getStorageSync('motorcycleList') || [];

    // 查找数组中是否存在指定 motorcycleName 的元素
    let foundIndex = -1;
    for (let i = 0; i < motorcycleList.length; i++) {
      if (motorcycleList[i].motorcycleName === motorcycleName) {
        foundIndex = i;
        break;
      }
    }

    if (foundIndex !== -1) {
      // 若存在，则更新其 otr 值
      motorcycleList[foundIndex].otr = otr;
      motorcycleList[foundIndex].order += 1;
    } else {
      // 若不存在，则添加一个新元素
      const maxOrder = Math.max(...motorcycleList.map(item => item.order))
      motorcycleList.push({
        motorcycleName: motorcycleName,
        otr: otr,
        order: maxOrder + 1
      });
    }
    // 将更新后的数组存回本地存储
    wx.setStorageSync('motorcycleList', motorcycleList);
    this.backToMotocycleListPage()
  },
  handleSaveThisMotorcycleClick() {
    if (this.data.motorcycleName) {
      this.updateMotorcycleList(this.data.motorcycleName, this.data.otr)
    } else {
      this.setData({
        showWithInput: true,
        motorcycleName: ''
      });
    }
  },
  handleInputChange(e) {
    if (e.detail.value) {
      this.setData({
        inputTips: '',
        motorcycleName: e.detail.value,
        motorcycleNameInputStatus: 'default'
      })
    } else {
      this.setData({
        inputTips: '车型名称不能为空!',
      motorcycleName: '',
        motorcycleNameInputStatus: 'error'
      })
    }
  },
  handleInputClear() {
    this.setData({
      motorcycleName: ''
    })
  },
  confirmDialog() {
    if (this.data.motorcycleName) {
      this.updateMotorcycleList(this.data.motorcycleName, this.data.otr)
    } else {
      this.setData({
        motorcycleNameInputStatus: 'error',
        inputTips: '车型名称不能为空!'
      })
    }
  },
  closeDialog() {
    this.setData({
      showWithInput: false,
      motorcycleName: '',
      motorcycleNameInputStatus: 'default',
      inputTips: ''
    });
  },
  backToMotocycleListPage() {
    wx.reLaunch ({
      url: '../../MotorcycleListPage/index/index',
    })
  }
});
